package com.MedDroid.task;

import android.content.Intent;
import android.os.AsyncTask;
import com.MedDroid.MainApp;
import com.MedDroid.activity.LoginActivity;
import com.MedDroid.activity.MainMenuActivity;
import com.MedDroid.control.AuthenticationControl;
import com.MedDroid.entities.User;

import java.lang.ref.WeakReference;

/**
 * Created with IntelliJ IDEA.
 * User: Romen
 * Date: 01/12/13
 * Time: 8:04 PM
 * Description:
 */
public class LoginTask extends AsyncTask<String, Void, User>
{
	AuthenticationControl AuthenticationC;
	WeakReference<LoginActivity> LoginPage;

	public LoginTask(AuthenticationControl Auth, LoginActivity activity)
	{
		AuthenticationC = Auth;
		LoginPage = new WeakReference<LoginActivity>(activity);
	}

	@Override
	protected User doInBackground(String... strings)
	{
		User LoginUser;
		if (AuthenticationC.attemptLogin(strings[0],strings[1]))
		{
			MainApp.log("Login Success.");
			return AuthenticationC.getLoginUser();
		}
		else
		{
			MainApp.log("attemptLogin Failed. Wrong Login Name or Password.");
			return null;
		}
	}

	@Override
	protected void onPostExecute(User LoginUser)
	{
		if (LoginUser != null)
		{
			LoginPage.get().EditUsername.setText("");
			LoginPage.get().EditPassword.setText("");
			Intent intent = new Intent (LoginPage.get(), MainMenuActivity.class);//creates the intent for the new activity
			LoginPage.get().startActivity(intent);//starts the activity
		}
		else
		{
			//Report some kind of failure to log in
			MainApp.log("Login Failed.");
		}
	}
}
